package utils

import (
	"bytes"
	"dingbot/config"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

const (
	//repo      = "hutao01-miku/cdn_Picgo" // 你的仓库 repo
	cutToken  = "ghp_CPGeUS8UpWNGR9H"   // 你的 Token 的前部分
	tailToken = "L9dRVhFWHfmpXtA1Sx63q" // 你的 Token 的尾部分
)

func ToPicture() (string, error) {
	conf := config.GetConfig()
	imagePath := "image1.jpg" // 图片文件的路径

	content, err := readFileContent(imagePath)
	if err != nil {
		fmt.Println("Error reading file content:", err)
		return "图片生成错误", err
	}

	path := generatePath()
	imageURL := fmt.Sprintf("https://api.github.com/repos/%s/contents/%s", conf.Token.CutToken, path)

	body := map[string]interface{}{
		"branch":  "main",
		"message": "upload",
		"content": content,
		"path":    path,
	}

	jsonBody, err := json.Marshal(body)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return "图片生成错误", err
	}

	req, err := http.NewRequest("PUT", imageURL, bytes.NewBuffer(jsonBody))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return "图片生成错误", err
	}

	req.Header.Set("Authorization", fmt.Sprintf("token %s%s", conf.Token.CutToken, conf.Token.TailToken))
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{Timeout: 30 * time.Second}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return "图片生成错误", err
	}
	defer resp.Body.Close()

	respBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return "图片生成错误", err
	}

	var responseData map[string]interface{}
	if err := json.Unmarshal(respBody, &responseData); err != nil {
		fmt.Println("Error unmarshalling response:", err)
		return "图片生成错误", err
	}

	if _, ok := responseData["content"].(map[string]interface{})["download_url"].(string); ok {
		fastlyURL := fmt.Sprintf("https://gcore.jsdelivr.net/gh/%s@main/%s", conf.Repository.Repo, path)
		fmt.Println("生成成功:", fastlyURL)
		return fastlyURL, nil
	} else {
		fmt.Println("Error: Unable to extract image link from response")
	}
	return "生成错误", err
}

func generatePath() string {
	d := time.Now()
	return fmt.Sprintf("%d/%d/%d%s", d.Year(), d.Month(), d.UnixNano(), ".png")
}

func readFileContent(filePath string) (string, error) {
	file, err := os.Open(filePath)
	if err != nil {
		return "", err
	}
	defer file.Close()

	content, err := ioutil.ReadAll(file)
	if err != nil {
		return "", err
	}

	return base64.StdEncoding.EncodeToString(content), nil
}
